# -*- coding: utf-8 -*-
# &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
# Odoo Connector
# QQ:35350428
# 邮件:sale@100china.cn
# 手机：13584935775
# 作者：wangguangjian
# 公司网址： www.odoo.pw  www.100china.cn
# Copyright 昆山一百计算机有限公司 2012-2016 Amos
# 日期：15/5/27
# &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&

import logging
from odoo import api, fields, models, tools, SUPERUSER_ID, _
from odoo.exceptions import AccessDenied, AccessError, UserError, ValidationError
from odoo.osv import expression

_logger = logging.getLogger(__name__)


class amos_res_groups(models.Model):
    amos_menu_ids = []
    _inherit = "res.groups"
    _order = 'id asc'

    inherit_base_id = fields.Many2one('res.groups', string=u'底层')
    authority_id = fields.Many2one('res.groups.name', string=u'权限名称')
    model_ok = fields.Many2many('ir.model', 'amos_groups_model_rel', 'groups_id', 'model_id', string=u"模块")
    value = fields.Char(string=u'值')
    filename = fields.Char(string=u'文件夹名称',help=u'代码生成时的文件夹名称')
    is_fields = fields.Boolean(default=False, string=u'是否字段权限', track_visibility='onchange')

    fields_name = fields.Many2one('ir.model.fields', string=u'字段名称')
    state = fields.Selection([
        ('draft', u'草稿'),
        ('cancel', u'取消'),
        ('done', u'已生成')
    ], string=u'状态', default='draft')



    @api.multi
    @api.onchange('is_fields')
    def onchange_is_fields(self):
        res = {}
        if self.is_fields:
            obj = self.env['ir.module.category'].search([('name', '=', u'字段权限')], order="sequence, id desc", limit=1)
            if obj:
                res['category_id'] = obj.id
                res['filename'] = 'Amos_Groups_Fields'
            else:
                res['category_id'] = False
        return {'value': res}

    @api.multi
    def onchange_authority_id(self,authority_id):
        res = {}
        if authority_id:
            groups = self.env['res.groups.name'].browse(authority_id)
            if self.name == False:
                res['name'] = groups.name
            else:
                res['name'] = self.name
        return {'value': res}


    # @api.multi
    # def add_button_groups(self):
    #     self.ensure_one()
    #     address_form_id = self.env.ref('Amos_Groups_Tools.view_form_groups_wizard').id
    #     return {'type': 'ir.actions.act_window',
    #             'res_model': 'groups.wizard',
    #             'view_mode': 'form',
    #             'views': [(address_form_id, 'form')],
    #             'res_id': False,
    #             'target': 'new',
    #             'flags': {'form': {'action_buttons': True}}}


    @api.multi
    def button_admin(self):

        groups = self.search([])
        for line in groups:
            list1 = line.users.ids
            list1.append(self._uid)
            list2 =sorted(set(list1), key=list1.index)
            values = {
                'users': [(6, 0, list2)],
            }
            line.sudo().write(values)
        return True

    @api.multi
    def but_refresh(self):
        return True

    @api.multi
    def but_done(self):

        # if self._context['authority_id'] == False:
            # raise UserError(u'权限名称未选择!')

        for model in self:
            model.make_security()
            state = 'done'
            model.write({'state': state})
        return True

    @api.multi
    def amos_access(self):
        obj =self.env['ir.model.access']
        obj_model = self.env['ir.model']
        if self._context['perm'] == 'access_create':
            instructors = self
            for instructor in instructors.model_ok:
                for field in instructor.field_id:
                    if field.ttype == 'many2one' or field.ttype == 'one2many' or field.ttype == 'many2many':
                        model_id = obj_model.search([('model', '=', field.relation)])
                        model_ = obj.search(
                                            [('group_id', '=', self.id), ('model_id', '=', model_id[0].id)])
                        if len(model_) == 0:
                            parm = {
                                'model_id': model_id[0].id,
                                'group_id': self.id,
                                'name': instructors.name,}
                            id = obj.create(parm)
                model_id = obj_model.search([('model', '=', instructor.model)])
                model_ = obj.search([('group_id', '=', self.id), ('model_id', '=', model_id[0].id)])
                if len(model_) == 0:
                    parm = {
                        'model_id': model_id[0].id,
                        'group_id': self.id,
                        'name': instructors.name,}
                    id = obj.create(parm)
            if instructors.inherit_base_id != False:
                for model in instructors.inherit_base_id.model_access:
                    model_ = obj.search(
                                        [('group_id', '=', self.id), ('model_id', '=', model.model_id.id)])
                    if len(model_) == 0:
                        parm = {
                            'model_id': model.model_id.id,
                            'group_id': self.id,
                            'name': instructors.name,
                            'perm_read': model.perm_read,
                            'perm_write': model.perm_write,
                            'perm_create': model.perm_create,
                            'perm_unlink': model.perm_unlink,
                        }
                        id = obj.create(parm)
        elif self._context['perm'] == 'access_base':
            instructors = self
            if instructors.inherit_base_id != False:
                for model in instructors.inherit_base_id.model_access:
                    model_ = obj.search(
                                        [('group_id', '=', self.id), ('model_id', '=', model.model_id.id)])
                    if len(model_) == 0:
                        parm = {
                            'model_id': model.model_id.id,
                            'group_id': self.id,
                            'name': instructors.name,
                            'perm_read': model.perm_read,
                            'perm_write': model.perm_write,
                            'perm_create': model.perm_create,
                            'perm_unlink': model.perm_unlink,
                        }
                        id = obj.create(parm)
                    else:
                        parm = {
                            'perm_read': model.perm_read,
                            'perm_write': model.perm_write,
                            'perm_create': model.perm_create,
                            'perm_unlink': model.perm_unlink,
                            'name': instructors.name,
                        }
                        self.write(parm)
        elif self._context['perm'] == 'access_unlink':
            obj.search([('group_id', '=', self.id)]).unlink()
        elif self._context['perm'] == 'access_menu':
            amos_menu_ids = []
            obj_actions = self.env['ir.actions.act_window']
            obj_menu = self.env['ir.ui.menu']
            # 当前的对象 找所有事件，每一个事件都去找菜单，如果存在就一直向上找 只到顶层结束
            # 所有菜单ID 存入数组，去重再抛入系统
            instructors = self
            actions_arr = []
            menu = []
            for instructor in instructors.model_ok:
                actions_id = obj_actions.search( [('res_model', '=', instructor.model)])
                actions_arr += actions_id.ids
            actions_list = {}.fromkeys(actions_arr).keys()
            if len(actions_list) == 0:
                return True
            for m in actions_list:
                actions_menu = obj_menu.search_read( [('action', '=','ir.actions.act_window,%s' % m)],['id'])
                if len(actions_menu) > 0:
                    menu.append(actions_menu[0]['id'])
            self.amos_menu_ids += menu
            h = self.amos_menu(menu)
            # 排序

            menu_list = {}.fromkeys(self.amos_menu_ids).keys()
            parm = {
                'menu_access': [(6, 0, sorted(menu_list, reverse=False))],
            }
            self.write(parm)
        else:
            instructors = self
            for instructor in instructors.model_access:

                # print instructors.inherit_base_id.model_access._ids

                if instructor.model_id.id in []:
                    pass

                parm = {
                    self._context['perm']: bool(self._context['perm_value']),
                }
                instructor.write(parm)

        return True

    @api.multi
    def amos_menu(self,ids):
        id_list = []
        obj_menu = self.env['ir.ui.menu']
        for id in ids:
            records = obj_menu.browse(id)
            if records.parent_id:
                id_list.append(records.parent_id.id)
        self.amos_menu_ids += id_list
        if len(id_list) > 0:
            self.amos_menu(id_list)
        return True


class amos_res_rule(models.Model):
    _inherit = "ir.rule"

    is_rule = fields.Boolean(u"更新规则", help=u'如果为True，点击生成规则，会把自定义规则更新到Domain 过滤器,为False不更新')
    rule_amos = fields.One2many('ir.rule.formula', 'rule_line', string=u"规则")

    @api.multi
    def _get_groups(self, *args):
        # 如果父级id存在找到组，然后返回默认参数到界面上
        if args[0].has_key('default_parent_id') == True:
            obj = self.env[args[0]['active_model']]
            records = obj.read(int(args[0]['active_id']), ['group_id'])
            return [records['group_id'][0]]
        return False

    _defaults = {
        'groups': _get_groups,
    }

    @api.multi
    def amos_formula(self):
        # 把所有规则拼接到 Domain 过滤器
        rule = ''
        if self.is_rule == True:
            for r in self.rule_amos:
                if r.state == False:
                    rule += "%s," % (r.formula)
                else:
                    rule += "('%s','%s',%s)," % (r.fields_id.name, r.state, r.formula)

            print rule

            rule =  rule[:-1]

            parm = {
                'domain_force': '[' + rule + ']',
            }
            self.write(parm)
        action_rec = self.env['ir.model.data'].xmlid_to_object('base.view_rule_form')
        return {
            'type': 'ir.actions.act_window',
            'view_type': 'form',
            'view_mode': 'form',
            'res_model': self._name,
            'views': [(action_rec.id, 'form')],
            'view_id': action_rec.id,
            'res_id': self.id,
            'target': 'current',
            'nodestroy': True,
        }


class amos_res_groups_ir_rule_formula(models.Model):
    _name = "ir.rule.formula"
    _description = "ir.rule.formula"

    rule_line = fields.Many2one('ir.rule', string=u'规则', required=True, ondelete='cascade')
    sequence = fields.Integer(string=u'排序')

    name = fields.Char(string=u'公式名称')
    fields_id = fields.Many2one('ir.model.fields', string=u'字段', required=True)

    state = fields.Selection([
        ('=', u'='),
        ('!=', u'!='),
        ('>', u'>'),
        ('>=', u'>='),
        ('<', u'<'),
        ('<=', u'<='),
        ('like', u'like'),
        ('ilike', u'ilike'),
        ('in', u'in'),
        ('not in', u'not in'),
        ('child_of', u'child_of'),
    ], string=u'条件', )

    formula = fields.Text(u'值')
    defaults = fields.Many2one('ir.rule.value.data', string=u'属性')


    @api.multi
    def onchange_defaults(self,defaults, fields_id):
        res = {}
        if defaults and fields_id:
            value_data = self.env['ir.rule.value.data'].browse(defaults)
            fields = self.env['ir.model.fields'].browse(fields_id)
            res['formula'] = value_data.value.replace('%s', fields.name)
        return {'value': res}


class amos_res_groups_ir_rule_value_data(models.Model):
    _name = "ir.rule.value.data"
    _description = "ir.rule.value.data"

    name = fields.Char(string=u'名称')
    value = fields.Char(string=u'值')


class amos_res_groups_name(models.Model):
    _name = "res.groups.name"
    _description = "res.groups.name"

    name = fields.Char(string=u'名称')
    value = fields.Char(string=u'值')


class ir_model_access(models.Model):
    _inherit = "ir.model.access"

    field_id = fields.One2many(related='model_id.field_id',  string=u'字段')


    @api.multi
    def open_rule(self):
        #:::::弹出规格写默认值
        context = dict(self.env.context or {})

        context['default_domain_force'] = "[(1,'=',1)]"
        context['default_groups'] = [(6, 0, [self.group_id.id])]
        context['default_model_id'] = self.model_id.id
        context['default_name'] = u'%s-%s' % (self.model_id.name,self.group_id.name)
        return {
            'name': u'设置规则',
            'view_type': 'form',
            'view_mode': 'form',
            'res_model': 'ir.rule',
            'view_id': self.env.ref('Amos_Groups_Tools.odoo_view_rule_form').id,
            'type': 'ir.actions.act_window',
            'res_id': False,
            'context': context,
            'target': 'new'
        }

    @api.multi
    def open_model_field(self):
        #:::::弹出当前列表 显示是不是已关联权限
        context = dict(self.env.context or {})
        context['group_id'] = self.group_id.id
        return {
            'name': u'字段权限配置',
            'view_type': 'form',
            'view_mode': 'form',
            'res_model': 'ir.model',
            'view_id': self.env.ref('Amos_Groups_Tools.view_form_ir_model_field_group_wizard').id,
            'type': 'ir.actions.act_window',
            'res_id': self.model_id.id,
            'context': context,
            'target': 'current',
        }





class ir_model(models.Model):
    _inherit = "ir.model"

    group_id = fields.Integer(string=u'权限', default=0)


    # @api.multi
    # def read(self, fields=None, load='_classic_read'):
    #     result = super(ir_model, self).read(fields, load=load)
    #     for values in result:
    #         if 'group_id' in fields:
    #             if self._context.has_key('group_id'):
    #                 value = {
    #                     'group_id': self._context['group_id'],
    #                 }
    #                 self.sudo().write(value)
    #     return result

class ir_model_fields(models.Model):
    _inherit = "ir.model.fields"

    @api.multi
    def create_group(self):
        print self._context,'-------'
        context = dict(self._context or {})
        # values = {
        #     'groups': [(6, 0, [context.get('group_id')])],
        # }
        # obj = self.sudo().write(values)
        #
        self._cr.execute('insert into ir_model_fields_group_rel (field_id,group_id) values(%s,%s)' % (self.id, self.model_id.group_id))

        return True

    @api.multi
    def unlink_group(self):
        print self._context
        # context = dict(self._context or {})
        # values = {
        #     'groups': [(2, context.get('group_id'))],
        # }
        # obj = self.sudo().write(values)

        self._cr.execute('DELETE FROM ir_model_fields_group_rel WHERE field_id=%s and group_id=%s' % (self.id, self.model_id.group_id))

        return True



    @api.multi
    def create_groups(self):
        #:::::查询是不是存在
        fields = self.env['res.groups'].search([('is_fields', '=', True),('fields_name', '=', self.id)])
        if fields:
            raise UserError(u'警告：字段权限已存在')
        else:

            category = self.env['ir.module.category'].search([('name', '=', u'字段权限')], order="sequence, id desc", limit=1)
            values = {
                'name': self.model_id.name+'/'+self.field_description,
                'is_fields':True,
                'fields_name':self.id,
                'category_id':category.id,
                'filename':'Amos_Groups_Fields',
            }
            self.env['res.groups'].sudo().create(values)


